﻿using System;
using System.Collections.Concurrent;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.ServiceModel;
using System.ServiceModel.Activation;

using SBPweb.PROvibe.Server.Library.Services;
using SBPweb.PROvibe.Server.Modules.DataProvider.Contracts;

using SBPweb.PROvibe.Shared.Library.Components;

namespace SBPweb.PROvibe.Server.Modules.DataProvider
{

    public class DataProviderService : ServiceBase<IDataProviderService>, IDataProviderService
    {

        #region Fields

        private ConcurrentQueue<DbConnection> connections = new ConcurrentQueue<DbConnection>();

        #endregion

        #region Constructor logic

        public DataProviderService(IModule parentModule)
            : base(parentModule)
        {
        }

        #endregion

        #region Properties

        public override string Name
        {
            get
            {
                return "DataProviderService.SQL2008";
            }
        }

        public string ConnectionString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings[Constants.Connections.ConnectionStringKeys.Primary].ConnectionString;
            }
        }

        #endregion

        #region Methods

        protected override void OnInitialize()
        {
        }

        protected override void OnTerminate()
        {
            foreach (DbConnection connection in connections)
            {
                if (connection.State == ConnectionState.Open)
                {
                    connection.Close();
                }
                connection.Dispose();
            }
        }

        public DbConnection CreateConnection()
        {
            DbConnection connection = new SqlConnection(ConnectionString);
            connections.Enqueue(connection);
            connection.Open();
            return connection;
        }

        public DbConnection CreateConnection(string initialCatalog)
        {
            DbConnection connection = new SqlConnection(ConnectionString);
            connections.Enqueue(connection);
            connection.Open();
            connection.ChangeDatabase(initialCatalog);
            return connection;
        }

        #endregion

    }

}